// DriveNotes. Copyright (c) 2011, Andrei Senchuk. All rights reserved.
package net.taviscaron.drivenotes.web.auth;

import java.io.IOException;
import java.util.GregorianCalendar;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.taviscaron.drivenotes.shared.model.entity.User;
import net.taviscaron.drivenotes.shared.service.LoginService;
import net.taviscaron.drivenotes.web.core.Constants;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * Authorization Filter
 * @author Andrei Senchuk
 */
public class AuthorizationFilter extends OncePerRequestFilter {
    private LoginService loginService;

    @Override
    protected void initFilterBean() throws ServletException {
        super.initFilterBean();
        WebApplicationContext context =
                WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        loginService = (LoginService)context.getBean("loginService");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
            HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        AuthorizationData authorizationData = null;
        HttpSession session = request.getSession(false);
        if(session != null) {
            authorizationData = (AuthorizationData)session.getAttribute(Constants.AUTHORIZATION_DATA_ATTR_NAME);
            if(authorizationData != null) {
                authorizationData.setLastAccessTime(GregorianCalendar.getInstance().getTime());
                request.setAttribute(Constants.AUTHORIZATION_DATA_ATTR_NAME, authorizationData);
                User user = loginService.findById(authorizationData.getUserId());
                request.setAttribute(Constants.AUTHORIZED_USER_ATTR_NAME, user);
            }
        }

        String action = request.getParameter(Constants.ACTION_PARAM_NAME);
        if(authorizationData != null || !"/controller".equals(request.getServletPath()) || "login".equals(action) || "register".equals(action)) {
            chain.doFilter(request, response);
        } else {
            String url = String.format("%s/controller?%s=login", request.getContextPath(), Constants.ACTION_PARAM_NAME);
            response.sendRedirect(response.encodeRedirectURL(url));
        }
    }
}
